import { Body, Controller, Del, Inject, Param, Post, Put } from '@midwayjs/core'
import { Context } from '@midwayjs/koa'
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags
} from '@midwayjs/swagger'
import { Validate } from '@midwayjs/validate'
import { ExcelService } from '@ttou/midway-excel'

import { Permission } from '@/decorator'
import { DeleteDTO } from '@/dto'

import { CreatePostDTO, FindPostPageDTO, UpdatePostDTO } from './post.dto'
import { PostExportSerialize } from './post.serialize'
import { PostService } from './post.service'
import { GetPostPageVO } from './post.vo'

@ApiBearerAuth()
@ApiTags('系统/岗位接口')
@Controller('/system/post')
export class PostController {
  @Inject()
  ctx: Context

  @Inject()
  excelService: ExcelService

  @Inject()
  postService: PostService

  @ApiOperation({ summary: '获取岗位分页' })
  @ApiResponse({ status: 200, type: GetPostPageVO })
  @Permission('system:post:list')
  @Post('/page')
  @Validate()
  async getPostPage(@Body() dto: FindPostPageDTO) {
    return await this.postService.handleFindPage(dto)
  }

  @ApiOperation({ summary: '新建岗位' })
  @Permission('system:post:add')
  @Post('/create')
  @Validate()
  async createPost(@Body() dto: CreatePostDTO) {
    await this.postService.handleCreate(dto)
  }

  @ApiOperation({ summary: '更新岗位' })
  @Permission('system:post:edit')
  @Put('/update/:id')
  @Validate()
  async updatePost(@Param('id') id: string, @Body() dto: UpdatePostDTO) {
    await this.postService.handleUpdate(id, dto)
  }

  @ApiOperation({ summary: '删除岗位' })
  @Permission('system:post:remove')
  @Del('/delete')
  @Validate()
  async deletePost(@Body() dto: DeleteDTO) {
    await this.postService.handleDelete(dto)
  }

  @ApiOperation({ summary: '导出岗位分页' })
  @Permission('system:post:export')
  @Post('/export')
  @Validate()
  async exportPostPage(@Body() dto: FindPostPageDTO) {
    const { list } = await this.postService.handleFindPage(dto)

    const result = await this.excelService.handleExport({
      sheetName: '岗位',
      filename: '岗位报表',
      Cls: PostExportSerialize,
      data: list
    })

    this.ctx.set(result.headers)
    this.ctx.body = result.body
  }
}
